//
//  UserAccount.swift
//  MicroBlog
//
//  Created by QT on 15/7/30.
//  Copyright © 2015年 綦敦涛. All rights reserved.
//

import UIKit

class UserAccount: NSObject,NSCoding{
    
    //
    class var userLogon:Bool{
        return sharedAccount != nil
    }
    
    // 	用于调用access_token，接口获取授权后的access token。
    var access_token: String?
    //  access_token的生命周期，单位是秒数
    var expires_in: NSTimeInterval = 0{
        didSet{
         expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    //  过期日期
    var expiresDate: NSDate?
    //  当前授权用户的UID。
    var uid: String?
    //  友好显示名称
    var name: String?
    //  用户头像地址（高清），高清头像原图
    var avatar_large: String?
    
    //****************************字典转模型的初始化方法************************************
    init(dict: [String: AnyObject]){
        super.init()
        setValuesForKeysWithDictionary(dict)
//        expiresDate = NSDate(timeIntervalSinceNow: expires_in)
    }
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
    }
    //****************************字典转模型的初始化方法************************************
    
    
    override var description: String {
        let properties: [String] = ["access_token","expires_in","uid","expiresDate","name","avatar_large"]
        return "\(dictionaryWithValuesForKeys(properties))"
    }
    
    
    // MARK: - 给模型追加用户信息
    func loadUserInof(){
        
        NetWorkTools.sharedTools.loadUserInfo(self.uid!) { (result, error) -> () in
            if error != nil{
                return
            }
            // 根据网络回调结果设置name和avatar_hd
            self.name = result!["name"] as? String
            self.avatar_large = result!["avatar_large"] as? String
            
            // 设置成功，再次保存用户信息（添加了name和avatar_hd）属性
            self.saveAccount()
        }
        
    }
    
    

    // 保存用户账号
    func saveAccount(){
        NSKeyedArchiver .archiveRootObject(self, toFile: UserAccount.path!)

    }
    
    // 获取用户账号
    /*
    由于后续访问都会依赖token,每次都需要重新解档，每次解档都要对磁盘进行I/O操作，需要注意缓存
    
    解决方案：
        使用静态局部变量记录
    */
    static var userAccount: UserAccount?
    
    
    class var sharedAccount: UserAccount?{
    // 对上面代码的优化
        // 1.如果静态局部变量没有值,就解档给它一个
        if userAccount == nil{
            userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(path!) as? UserAccount
        }
        // 2.判断静态局部变量是否过期，返回
        if let data = userAccount?.expiresDate where data.compare(NSDate()) == NSComparisonResult.OrderedAscending{
        userAccount = nil
        }
        // 3. 返回userAccount
        
        return userAccount
}
    
    
    
    // MARK: - 归档 && 解档
    
    // 获取归档文件路径
    static private let path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last?.stringByAppendingPathComponent("account.plist")
    
    
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_hd")
    }
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        uid = aDecoder.decodeObjectForKey("uid") as? String
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_hd") as? String
        
    }
    
}
